package com.icesoft.base.manager.security.login.handle;


import com.icesoft.base.manager.entity.system.SysUserLoginRecord;
import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.service.system.SysUserLoginRecordService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;


/**
 * 注意通用事件处理有两个登录成功的事件<br/>
 * InteractiveAuthenticationSuccessEvent, AuthenticationSuccessEvent<br/>
 * InteractiveAuthenticationSuccessEvent表示通过自动交互的手段来登录成功，比如cookie自动登录<br/>
 */
@Component
@AllArgsConstructor
@Slf4j
public class LoginSuccessRecordEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
    private SysUserLoginRecordService sysUserLoginRecordService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        Authentication authentication = event.getAuthentication();
        SysUserLoginRecord sysUserLoginRecord = new SysUserLoginRecord();
        WebAuthenticationDetails details = (WebAuthenticationDetails) event.getAuthentication().getDetails();
        sysUserLoginRecord.setLoginIp(details.getRemoteAddress());
        sysUserLoginRecord.setLoginSuccess(true);
        sysUserLoginRecord.setUsername(authentication.getName());
        if (authentication.getPrincipal() instanceof AuthUser) {
            AuthUser authUser = (AuthUser) event.getAuthentication().getPrincipal();
            sysUserLoginRecord.setUserId(authUser.getId());
        }
        sysUserLoginRecordService.create(sysUserLoginRecord);
    }
}
